package cn.edu.sjtu.se.dslab.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.sjtu.se.dslab.component.data.DomainEntity;
import cn.edu.sjtu.se.dslab.exception.DBException;
import cn.edu.sjtu.se.dslab.project.EntityZone;
import cn.edu.sjtu.se.dslab.project.EntityZoneCategory;
import cn.edu.sjtu.se.dslab.project.Project;
import cn.edu.sjtu.se.dslab.service.IDomainEntityService;
import cn.edu.sjtu.se.dslab.service.IEntityZoneCategoryService;
import cn.edu.sjtu.se.dslab.service.IEntityZoneService;
import cn.edu.sjtu.se.dslab.service.IProjectService;

@Controller
@RequestMapping(value="/entityZone")
public class EntityZoneController {

	private static final Logger logger = Logger
			.getLogger(EntityZoneController.class);

	@Resource(name = "domainEntityService")
	IDomainEntityService domainEntityService;
	
	@Resource(name = "entityZoneCategoryService")
	IEntityZoneCategoryService entityZoneCategoryService;
	
	@Resource(name = "entityZoneService")
	IEntityZoneService entityZoneService;
	
	@Resource(name = "projectService")
	IProjectService projectService;
	
	
	@RequestMapping(value = "/{projectId}/list", method = RequestMethod.GET)
	public ModelAndView getEntityZoneByProject(@PathVariable(value = "projectId")long projectId){
		ModelAndView mav = new ModelAndView();
		
		List<EntityZoneCategory> entityZoneCategorys = entityZoneCategoryService.getEntityZoneCategoryByProject(projectId);
		mav.addObject("entityZoneCategorys", entityZoneCategorys);
		
		List<EntityZone> entityZones = entityZoneService.getEntityZoneByProject(projectId);
		mav.addObject("entityZones", entityZones);
		for (EntityZone entityZone : entityZones){
			DomainEntity entity = domainEntityService.getDomainEntityByUri(entityZone.getEntityUri());
			if (entity!=null){
				entityZone.setEntityUri(entity.getName());
			}
		}
		
		List<Project> projects = projectService.getProjectList();
		mav.addObject("projects", projects.iterator());
		
		Project project = projectService.getProjectById(projectId);
		mav.addObject("project", project);
		
		List<DomainEntity> domainEntities = domainEntityService
				.getAllDomainEntity();
		mav.addObject("domainEntitys", domainEntities);
		
		mav.setViewName("editEntityZone");
		return mav;
	}
	
	
	@RequestMapping(value = "/{type}/{projectId}/add", method = RequestMethod.POST)
	public String addEntityZone(@PathVariable(value = "projectId")long projectId, 
			@PathVariable(value = "type")String type, EntityZone entityZone, long entityZoneCategoryId){
		//List<EntityZone> entityZones = entityZoneService.getEntityZoneByProject(projectId);
		//mav.addObject("entityZones", entityZones);
		EntityZoneCategory entityZoneCategory = entityZoneCategoryService.getEntityZoneCategoryById(entityZoneCategoryId);
		if (entityZoneCategory != null){
			entityZone.setEntityZoneCategory(entityZoneCategory);
			entityZoneService.addEntityZone(entityZone, projectId);
		}
		StringBuilder sb = new StringBuilder("redirect:/");
		sb.append(type).append("/").append(projectId).append("/entityZone/edit");
		return sb.toString();
	}
	
//	@RequestMapping(value = "/{type}/{entityZoneCategoryId}/add", method = RequestMethod.POST)
//	public String addEntityZone(@PathVariable(value = "entityZoneCategoryId")long entityZoneCategoryId, 
//			@PathVariable(value = "type")String type, EntityZone entityZone){
//		ModelAndView mav = new ModelAndView();
//		EntityZoneCategory entityZoneCategory = entityZoneCategoryService.getEntityZoneCategoryById(entityZoneCategoryId);
//		Project project = entityZoneCategory.getProject();
//		if (project != null){
//			List<EntityZone> entityZones = entityZoneService.getEntityZoneByProject(project.getId());
//			mav.addObject("entityZones", entityZones);
//			entityZoneService.addEntityZone(entityZone, project.getId());
//		}
//		StringBuilder sb = new StringBuilder("redirect:/");
//		sb.append(type).append("/").append(project.getId()).append("/entityZone/edit");
//		return sb.toString();
//	}
	
	@RequestMapping(value = "/{projectId}/add/{categoryId}", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> addEntityZone(@PathVariable(value = "projectId")long projectId,@PathVariable(value = "categoryId")String categoryId,
			@RequestBody EntityZone entityZone){
		Map<String, String> responseMap = new HashMap<String, String>();
		logger.info("Add EntityZone name=" + entityZone.getName() + " size:" + entityZone.getSize() + " entityUri:" + entityZone.getEntityUri());
		EntityZoneCategory entityZoneCategory = entityZoneCategoryService.getEntityZoneCategoryById(Long.parseLong(categoryId));
		boolean result = false;
		if (entityZoneCategory != null){
			entityZone.setEntityZoneCategory(entityZoneCategory);
			result = entityZoneService.addEntityZone(entityZone, projectId);
		}
		logger.info(result);
		if (result){
			responseMap.put("result", Boolean.TRUE.toString());
		}else{
			responseMap.put("result", Boolean.FALSE.toString());
		}
		return responseMap;
	}
	
	
	@RequestMapping(value = "/{projectId}/{entityZoneId}", method = RequestMethod.DELETE)
	@ResponseBody
	public Map<String, String> deleteEntityZone(@PathVariable(value = "projectId")long projectId, 
			@PathVariable(value = "entityZoneId")long entityZoneId){
		logger.info("Delete entity zone" + entityZoneId);
		boolean result = entityZoneService.deleteEntityZoneById(entityZoneId);
		Map<String, String> responseMap = new HashMap<String, String>();
		if (result){
			responseMap.put("result", Boolean.TRUE.toString());
		}else{
			responseMap.put("result", Boolean.FALSE.toString());
		}
		return responseMap;
	}
	

	@ExceptionHandler({ IOException.class, DBException.class })
	public ResponseEntity<String> handleIOException(IOException ex) {
		// prepare responseEntity
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.TEXT_PLAIN);
		ResponseEntity<String> responseEntity = new ResponseEntity<String>(
				"The server has some errors,please try later!", headers,
				HttpStatus.OK);
		return responseEntity;
	}
	
	
	
	
	
	
}
